// 四、手写实现 MyPromise 源码，要求：尽可能怀远 Promise 中的每一个 API，并通过注释的方式描述思路和原理
// Promise 的三种状态 pending 等待 fulfilled 成功 rejected 失败

// 定义状态常量，为了复用和提示
const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected' // 失败

// 创建 MyPromise
class MyPromise {
  // 通过构造器接收执行器
  constructor (executor) {
    try {
      executor(this.resolve, this.reject) // 执行器会立即执行
    } catch (e) {
      // 异常情况直接执行失败
      this.reject(e) // this 指向 MyPromise 这个类
    }
  }
  // promise 状态 默认为 pending
  status = PENDING
  // 成功后的返回值
  value = undefined
  // 失败的返回原因
  reason = undefined
  // 成功回调
  successCallback = []
  // 失败回调
  failCallback = []

  resolve = value => {
    // 如果状态不是等待，阻止程序向下执行
    if (this.status !== PENDING) return
    // 将状态更改为 成功
    this.status = FULFILLED
    // 存储成功之后的值
    this.value = value
    // 执行成功后的回调
    while (this.successCallback.length) this.successCallback.shift()(this.value) // 每执行一次，就删除最前面一个
  }

  reject = reason => {
    if (this.status !== PENDING) return
    // 状态更改为 失败
    this.status = REJECTED
    // 保存失败原因
    this.reason = reason
    // 调用失败回调
    while (this.failCallback.length) this.failCallback.shift()(this.reason)
  }

  then (successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value
    failCallback = failCallback ? failCallback : reason => { throw reason }
    let promise2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        // 成功状态
        setTimeout(() => {
          try {
            let x = successCallback(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        // 失败状态
        setTimeout(() => {
          try {
            let x = failCallback(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else {
        // 等待状态
        // 将 成功和失败回调 存储起来
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
      }
    })
    return promise2
  }

  catch (failCallback) {
    return this.then(undefined, failCallback)
  }

  finally (callback) {
    return this.then(value => {
      return MyPromise.resolve(callback()).then(() => value)
    }, reason => {
      return MyPromise.resolve(callback()).then(() => { throw reason })
    })
  }
  
  static resolve (value) {
    if (value instanceof MyPromise) return value
    return new MyPromise(resolve => resolve(value))
  }

  static reject (reason) {
    return new MyPromise(reject => reject(reason))
  }

  // all
  static all (array) { // 接收一个数组参数
    let result = [] // 存储执行结果
    let index = 0
    return new MyPromise((resolve, reject) => {
      function addData (key, value) {
        result[key] = value
        index++
        if (index === array.length) { // 等待所有异步执行完成
          resolve(result)
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i]
        if (current instanceof MyPromise) {
          // 如果是promise对象
          current.then(value => addData(i, value), reason => reject(reason))
        } else {
          addData(i, array[i])
        }
      }
    })

  }

  static race (array) {
    if (!Array.isArray(array)) throw new Error('race 参数必须是数组')
    return new MyPromise((resolve, reject) => {
      for (let i = 0; i < array.length; i++) {
        this.resolve(array[i]).then(value => {
          resolve(value)
        }, reason => {
          reject(reason)
        })
      }
    })
  }

  // any

}

function resolvePromise (promise2, x, resolve, reject) {
  // 判断 x 的值是普通值还是 promise 对象
  if (promise2 === x) {
    return reject('fail')
  }
  if (x instanceof MyPromise) {
    x.then(resolve, reject)
  } else { // x 是普通值
    resolve(x)
  }
}

module.exports = MyPromise